import dayjs from "dayjs";
import { AppRouterInstance } from "next/dist/shared/lib/app-router-context.shared-runtime";
import { ReadonlyURLSearchParams } from "next/navigation";

export const navUrl = (
  router: AppRouterInstance,
  pathname: string,
  search: ReadonlyURLSearchParams,
  values: any,
  callBack: (query: URLSearchParams) => URLSearchParams
) => {
  const params = new URLSearchParams(search);
  for (let k in values) {
    params.set(k, values[k] || "");
  }

  let query = callBack(params);
  // console.log(`${pathname}?${query.toString()}`);
  router.push(`${pathname}?${query.toString()}`);
};
const numReg = /^\d+$/;
export const getSearchQuery = (query: URLSearchParams) => {
  let params: any = Object.fromEntries(query.entries());
  for (let k in params) {
    const v = params[k];
    if (v === "") {
      delete params[k];
    }
    if (numReg.test(v)) {
      params[k] = Number(v);
    }
    if (v.indexOf("_") === 10) {
      const times = v.split("_");
      params[k] = [dayjs(times[0]), dayjs(times[1])];
    }
  }
  return params;
};
